package com.lianrui.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 功能描述：权限过滤器
 *
 * @author LJQ
 *
 * 2015年12月15日 上午1:42:16
 */
@SuppressWarnings("unused")
public class AccessControlFilter implements Filter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AccessControlFilter.class);
	
	private FilterConfig filterConfig = null;

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		// 参数为true时，返回的是null; 没有参数或是false则返回新的session
		HttpSession session = httpRequest.getSession();
		String header = httpRequest.getHeader("X-Requested-With");
		String path = httpRequest.getRequestURI();

		// 登录请求,静态资源访问地址不过滤
		String[] notFilter = new String[] { "login", "logout", "statics", "main", "monitor", "test" };
		boolean doFilter = true;
		for (String s : notFilter) {
			if (path.indexOf(s) != -1) {
				doFilter = false;
				break;
			}
		}

		// 默认登录地址不过滤
		String contextPath = httpRequest.getContextPath();
		if (contextPath.equals(path) || contextPath.equals(path.substring(0, path.lastIndexOf("/")))) {
			doFilter = false;
		}

		if (doFilter) {//Ajax请求
			if (header != null && "XMLHttpRequest".equalsIgnoreCase(header)) {
				// 判断是否是session过期，如果是执行下边的代码
				if (session == null) {
					httpResponse.setHeader("sessionstatus", "timeout");
				}
			} else {// 非ajax请求
				if (session == null) {
					// 进入超时提示页面
					httpResponse.sendRedirect(httpRequest.getContextPath() + "/login?error=2");
					return;
				}
			}
		}

		chain.doFilter(httpRequest, httpResponse);
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;
	}

}
